package com.bndg.browser.fargment

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.net.http.SslError
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.view.KeyEvent
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.webkit.DownloadListener
import android.webkit.SslErrorHandler
import android.webkit.ValueCallback
import android.webkit.WebResourceError
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebView
import android.widget.EditText
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.widget.PopupMenu
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.FileUtils
import com.bndg.browser.R
import com.bndg.browser.client.AndroidInterface
import com.bndg.browser.client.MiddlewareChromeClient
import com.bndg.browser.client.MiddlewareWebViewClient
import com.bndg.browser.db.AppDatabase
import com.bndg.browser.db.History
import com.bndg.browser.ui.CommonActivity
import com.bndg.browser.util.OtherUtils
import com.bndg.browser.util.Trace
import com.bndg.browser.widget.SmartRefreshWebLayout
import com.download.library.DownloadImpl
import com.download.library.DownloadListenerAdapter
import com.download.library.DownloadingListener
import com.download.library.Extra
import com.download.library.ResourceRequest
import com.ferfalk.simplesearchview.SimpleSearchView
import com.hjq.base.BaseFragment
import com.hjq.toast.ToastUtils
import com.just.agentweb.AbsAgentWebSettings
import com.just.agentweb.AgentWeb
import com.just.agentweb.AgentWebConfig
import com.just.agentweb.DefaultDownloadImpl
import com.just.agentweb.DefaultWebClient
import com.just.agentweb.IAgentWebSettings
import com.just.agentweb.IWebLayout
import com.just.agentweb.MiddlewareWebChromeBase
import com.just.agentweb.MiddlewareWebClientBase
import com.just.agentweb.PermissionInterceptor
import com.just.agentweb.WebChromeClient
import com.just.agentweb.WebListenerManager
import com.just.agentweb.WebViewClient
import com.just.agentweb.filechooser.FileCompressor
import com.just.agentweb.filechooser.FileCompressor.FileCompressEngine
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File
import java.io.FileOutputStream
import java.net.URL


/**
 * Created by cenxiaozhong on 2017/5/15.
 * source code  https://github.com/Justson/AgentWeb
 */
class AgentWebFragment : BaseFragment<CommonActivity>(), FragmentKeyDown, FileCompressEngine {
    private var mBackImageView: ImageView? = null
    private var mLineView: View? = null
    private var mFinishImageView: ImageView? = null
    private var mTitleTextView: TextView? = null
    protected var mAgentWeb: AgentWeb? = null
    private var mMoreImageView: ImageView? = null
    private val mPopupMenu: PopupMenu? = null
    private var mMiddleWareWebClient: MiddlewareWebClientBase? = null
    private var mMiddleWareWebChrome: MiddlewareWebChromeBase? = null
    private var mSmartRefreshWebLayout: SmartRefreshWebLayout? = null
    override fun getLayoutId(): Int {
        return R.layout.fragment_agentweb
    }

    override fun initView() {
        originUrl = getBundle()?.getString(URL_KEY).toString()
        mAgentWeb = AgentWeb.with(this) //
            .setAgentWebParent(
                findViewById(R.id.linearLayout) as LinearLayout?, -1, LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
                )
            ) //传入AgentWeb的父控件。
            .useDefaultIndicator(-1, 3) //设置进度条颜色与高度，-1为默认值，高度为2，单位为dp。
            .setAgentWebWebSettings(iAgentWebSettings) //设置 IAgentWebSettings。
            .setWebViewClient(mWebViewClient) //WebViewClient ， 与 WebView 使用一致 ，但是请勿获取WebView调用setWebViewClient(xx)方法了,会覆盖AgentWeb DefaultWebClient,同时相应的中间件也会失效。
            .setWebChromeClient(mWebChromeClient) //WebChromeClient
            .setWebLayout(webLayout)
            .setPermissionInterceptor(mPermissionInterceptor) //权限拦截 2.0.0 加入。
            .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK) //严格模式 Android 4.2.2 以下会放弃注入对象 ，使用AgentWebView没影响。
            .setMainFrameErrorView(
                com.just.agentweb.R.layout.agentweb_error_page,
                -1
            ) //参数1是错误显示的布局，参数2点击刷新控件ID -1表示点击整个布局都刷新， AgentWeb 3.0.0 加入。
            .useMiddlewareWebChrome(middlewareWebChrome) //设置WebChromeClient中间件，支持多个WebChromeClient，AgentWeb 3.0.0 加入。
//            .additionalHttpHeader(originUrl, "cookie", "41bc7ddf04a26b91803f6b11817a5a1c")
            .useMiddlewareWebClient(middlewareWebClient) //设置WebViewClient中间件，支持多个WebViewClient， AgentWeb 3.0.0 加入。
            .setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.ASK) //打开其他页面时，弹窗质询用户前往其他应用 AgentWeb 3.0.0 加入。
            .interceptUnkownUrl() //拦截找不到相关页面的Url AgentWeb 3.0.0 加入。
            .createAgentWeb() //创建AgentWeb。
            .ready() //设置 WebSettings。
            .go(originUrl) //WebView载入该url地址的页面并显示。
        mAgentWeb?.let {
            //注入对象
            it.jsInterfaceHolder.apply {
                addJavaObject(
                    "android",
                    AndroidInterface(mAgentWeb, getAttachActivity())
                )
            }
            it.webCreator.webView.settings.apply {
                setSupportZoom(true) // 启用缩放功能
                builtInZoomControls = true // 启用内置缩放控件
                displayZoomControls = false // 隐藏缩放控件（可选）
            }
        }
        AgentWebConfig.debug()

        mBackImageView = findViewById<ImageView>(R.id.iv_back)
        mLineView = findViewById(R.id.view_line)
        mFinishImageView = findViewById<ImageView>(R.id.iv_finish)
        mTitleTextView = findViewById<TextView>(R.id.toolbar_title)
        mMoreImageView = findViewById<ImageView>(R.id.iv_more)
        mSearchImageView = findViewById<ImageView>(R.id.iv_search)
        mSimpleSearchView = findViewById<SimpleSearchView>(R.id.search_view)
        setOnClickListener(R.id.iv_back, R.id.iv_finish, R.id.iv_more, R.id.iv_search)
        pageNavigator(View.GONE)
        mSimpleSearchView!!.setHint("请输入网址")
        val etForSearchView =
            mSimpleSearchView!!.findViewById<EditText>(com.ferfalk.simplesearchview.R.id.searchEditText)
        etForSearchView.imeOptions = EditorInfo.IME_ACTION_GO
        mSimpleSearchView?.setOnSearchViewListener(object : SimpleSearchView.SearchViewListener {
            override fun onSearchViewClosed() {
            }

            override fun onSearchViewClosedAnimation() {
            }

            override fun onSearchViewShown() {
                val url = mAgentWeb?.webCreator?.webView?.url
                Trace.d(url)
                etForSearchView?.setText(url)
                etForSearchView?.setSelection(etForSearchView.text?.length ?: 0)
            }

            override fun onSearchViewShownAnimation() {
            }
        })
        //        mSimpleSearchView.setSearchBackground(new ColorDrawable(getColorPrimary()));
        mSimpleSearchView!!.setOnQueryTextListener(object : SimpleSearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(s: String): Boolean {
                var completeUrl = s
                if (!completeUrl.startsWith("http")) {
                    completeUrl = "http://$s"
                }
                mAgentWeb?.urlLoader?.loadUrl(completeUrl)
                return false
            }

            override fun onQueryTextChange(s: String): Boolean {
                return false
            }

            override fun onQueryTextCleared(): Boolean {
                return false
            }
        })
        FileCompressor.getInstance().registerFileCompressEngine(this)

        // AgentWeb 没有把WebView的功能全面覆盖 ，所以某些设置 AgentWeb 没有提供 ， 请从WebView方面入手设置。
        mAgentWeb?.webCreator?.webView?.overScrollMode = WebView.OVER_SCROLL_NEVER
        //mAgentWeb.getWebCreator().getWebView()  获取WebView .
        val mSmartRefreshLayout = mSmartRefreshWebLayout!!.layout as SmartRefreshLayout
        mSmartRefreshLayout.setOnRefreshListener {
            mAgentWeb?.urlLoader?.reload()
            mSmartRefreshLayout.postDelayed({ mSmartRefreshLayout.finishRefresh() }, 2000)
        }
    }

    private val webLayout: IWebLayout<*, *>
        get() = SmartRefreshWebLayout(activity).also { this.mSmartRefreshWebLayout = it }

    override fun initData() {
    }

    /**
     * PermissionInterceptor 能达到 url1 允许授权， url2 拒绝授权的效果。
     * @param url
     * @param permissions
     * @param action
     * @return true 该Url对应页面请求权限进行拦截 ，false 表示不拦截。
     */
    protected var mPermissionInterceptor: PermissionInterceptor =
        PermissionInterceptor { url, permissions, action ->
            Trace.d("mUrl:$url  permission:$permissions action:$action")
            false
        }

    /**
     * AgentWeb 4.0.0 内部删除了 DownloadListener 监听 ，以及相关API ，将 Download 部分完全抽离出来独立一个库，
     * 如果你需要使用 AgentWeb Download 部分 ， 请依赖上 compile 'com.download.library:Downloader:4.1.1' ，
     * 如果你需要监听下载结果，请自定义 AgentWebSetting ， New 出 DefaultDownloadImpl
     * 实现进度或者结果监听，例如下面这个例子，如果你不需要监听进度，或者下载结果，下面 setDownloader 的例子可以忽略。
     * @param webView
     * @param downloadListener
     * @return WebListenerManager
     */
    val iAgentWebSettings: IAgentWebSettings<*>
        /**
         * @return IAgentWebSettings
         */
        get() = object : AbsAgentWebSettings() {
            private var settingsAgentWeb: AgentWeb? = null

            override fun bindAgentWebSupport(agentWeb: AgentWeb?) {
                this.settingsAgentWeb = agentWeb
            }

            override fun setDownloader(
                webView: WebView,
                downloadListener: DownloadListener?
            ): WebListenerManager {
                return super.setDownloader(webView,
                    object : DefaultDownloadImpl(
                        activity,
                        webView,
                        this.settingsAgentWeb?.permissionInterceptor
                    ) {
                        override fun createResourceRequest(url: String): ResourceRequest<*>? {
                            Trace.d(">>>>", "出现了请求: createResourceRequest")
                            val blockMaxTime = DownloadImpl.getInstance(context!!)
                                .url(url)
                                .quickProgress()
                                .addHeader("", "")
                                .setEnableIndicator(true)
                                .autoOpenIgnoreMD5()
                                .setRetry(5)
                                .setBlockMaxTime(100000L)
                            return blockMaxTime
                        }

                        override fun taskEnqueue(resourceRequest: ResourceRequest<*>?) {
                            Trace.d(">>>>", "执行下载？: $resourceRequest")
                            // alertdialog 提示是否下载
                            val alertDialog = AlertDialog.Builder(context!!)
                                .setTitle("下载")
                                .setMessage("是否下载？")
                                .setPositiveButton("下载") { _, _ ->
                                    resourceRequest?.enqueue(object : DownloadListenerAdapter() {
                                        override fun onStart(
                                            url: String,
                                            userAgent: String,
                                            contentDisposition: String?,
                                            mimetype: String,
                                            contentLength: Long,
                                            extra: Extra
                                        ) {
                                            super.onStart(
                                                url,
                                                userAgent,
                                                contentDisposition,
                                                mimetype,
                                                contentLength,
                                                extra
                                            )
                                        }

                                        @DownloadingListener.MainThread
                                        override fun onProgress(
                                            url: String,
                                            downloaded: Long,
                                            length: Long,
                                            usedTime: Long
                                        ) {
                                            super.onProgress(url, downloaded, length, usedTime)
                                        }

                                        override fun onResult(
                                            throwable: Throwable,
                                            path: Uri,
                                            url: String,
                                            extra: Extra
                                        ): Boolean {
                                            return super.onResult(throwable, path, url, extra)
                                        }
                                    })
                                }
                                .setNegativeButton("取消") { _, _ ->
                                }
                                .create().show()

                        }
                    })
            }
        }

    var originUrl: String = "http://cn.bing.com/"

    /**
     * 用于处理网页的交互和用户界面事件，例如获取网页标题、显示加载进度、处理 JavaScript 弹窗等。
     */
    protected var mWebChromeClient: WebChromeClient = object : WebChromeClient() {
        override fun onProgressChanged(view: WebView, newProgress: Int) {
            super.onProgressChanged(view, newProgress)
//            Trace.d( "onProgressChanged:$newProgress  view:$view")
        }

        override fun onReceivedIcon(p0: WebView?, p1: Bitmap?) {
            super.onReceivedIcon(p0, p1)
            Trace.d(">>>>", ": ")
        }

        override fun onReceivedTitle(view: WebView, title: String) {
            var title = title
            super.onReceivedTitle(view, title)
            if (mTitleTextView != null && !TextUtils.isEmpty(title)) {
                if (title.length > 10) {
                    title = title.substring(0, 10) + "..."
                }
            }
            mTitleTextView!!.text = title
            /*context?.let {
                lifecycleScope.launch(Dispatchers.IO) {
                    Trace.d(">>>>", "title $title oriurl: $originUrl")
                    AppDatabase.getInstance(it).historyDao()
                        .updateHistoryTitle(title, originUrl)
                }
            }*/
        }
    }

    /**
     * 注意，重写WebViewClient的方法,super.xxx()请务必正确调用， 如果没有调用super.xxx(),则无法执行DefaultWebClient的方法
     * 可能会影响到AgentWeb自带提供的功能,尽可能调用super.xxx()来完成洋葱模型
     * 用于处理网页加载和链接点击事件，决定是否在 WebView 中加载链接，或在外部浏览器中打开。
     */
    protected var mWebViewClient: WebViewClient = object : WebViewClient() {
        private val timer = HashMap<String, Long?>()

        override fun onReceivedError(
            view: WebView,
            request: WebResourceRequest,
            error: WebResourceError
        ) {
            super.onReceivedError(view, request, error)
        }

        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
            return super.shouldOverrideUrlLoading(view, request)
        }

        override fun shouldInterceptRequest(
            view: WebView,
            request: WebResourceRequest
        ): WebResourceResponse? {
            return super.shouldInterceptRequest(view, request)
        }

        override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
            Trace.d("view:" + view.hitTestResult)
            Trace.d("mWebViewClient shouldOverrideUrlLoading:$url")
            //优酷想唤起自己应用播放该视频 ， 下面拦截地址返回 true  则会在应用内 H5 播放 ，禁止优酷唤起播放该视频， 如果返回 false ， DefaultWebClient  会根据intent 协议处理 该地址 ， 首先匹配该应用存不存在 ，如果存在 ， 唤起该应用播放 ， 如果不存在 ， 则跳到应用市场下载该应用 .
            if (url.startsWith("intent://") && url.contains("com.youku.phone")) {
                return true
            }
            /*else if (isAlipay(view, mUrl))   //1.2.5开始不用调用该方法了 ，只要引入支付宝sdk即可 ， DefaultWebClient 默认会处理相应url调起支付宝
			    return true;*/
            return super.shouldOverrideUrlLoading(view, url)
        }

        override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
            super.onPageStarted(view, url, favicon)
            Trace.d("mUrl:$url onPageStarted  target:$originUrl")
            timer[url] = System.currentTimeMillis()
            if (url == originUrl) {
                pageNavigator(View.GONE)
            } else {
                pageNavigator(View.VISIBLE)
            }
            originUrl = url
        }

        override fun onPageFinished(view: WebView, url: String) {
            super.onPageFinished(view, url)
            // 读取 assets 文件夹中的 JavaScript 文件并注入
            OtherUtils.injectJavaScript(view, "inject_video.js")
            OtherUtils.injectJavaScript(view, "force_zoom.js")
            if (timer[url] != null) {
                val overTime = System.currentTimeMillis()
                val startTime = timer[url]
                Trace.d("  page mUrl:" + url + "  used time:" + (overTime - startTime!!))
            }
            val favicon = view.favicon
            val title = view.title ?: ""
            context?.let {
                lifecycleScope.launch(Dispatchers.IO) {
                    URL(url).host?.let { host ->
                        val historyList = AppDatabase.getInstance(it).historyDao()
                            .queryFavicon(host)
                        var favLocal = ""
                        if (favicon != null) {
                            if (historyList.isNotEmpty() && FileUtils.isFileExists(File(historyList[0].favicon!!))) {
                                favLocal = historyList[0].favicon!!
                            } else {
                                val file = File(it.filesDir, host + "_favicon.ico")
                                FileOutputStream(file).use { outputStream ->
                                    // 将 Bitmap 压缩为 PNG 格式并写入文件
                                    favicon.compress(Bitmap.CompressFormat.PNG, 100, outputStream)
                                }
                                favLocal = file.absolutePath
                                AppDatabase.getInstance(it).historyDao()
                                    .updateHistoryFavicon(favLocal, host)
                            }
                        } else {
                            Trace.d(">>>>", "fav is null")
                        }
                        Trace.d(">>>>", "insert: url $url")
                        AppDatabase.getInstance(it).historyDao()
                            .insertOrUpdate(History(title, host, url, "", favLocal))
                    }
                }
            }
        }

        /*错误页回调该方法 ， 如果重写了该方法， 上面传入了布局将不会显示 ， 交由开发者实现，注意参数对齐。*/ /* public void onMainFrameError(AbsAgentWebUIController agentWebUIController, WebView view, int errorCode, String description, String failingUrl) {

            Trace.d( "AgentWebFragment onMainFrameError");
            agentWebUIController.onMainFrameError(view,errorCode,description,failingUrl);

        }*/
        override fun onReceivedHttpError(
            view: WebView,
            request: WebResourceRequest,
            errorResponse: WebResourceResponse
        ) {
            super.onReceivedHttpError(view, request, errorResponse)
        }

        override fun onReceivedSslError(view: WebView, handler: SslErrorHandler, error: SslError) {
            handler.proceed()
            super.onReceivedSslError(view, handler, error)
        }

        override fun onReceivedError(
            view: WebView,
            errorCode: Int,
            description: String,
            failingUrl: String
        ) {
            super.onReceivedError(view, errorCode, description, failingUrl)
        }
    }

    private var mSimpleSearchView: SimpleSearchView? = null
    private var mSearchImageView: ImageView? = null

    private fun pageNavigator(tag: Int) {
        mBackImageView!!.visibility = tag
        mLineView!!.visibility = tag
    }

    override fun onClick(view: View) {
        val id = view.id
        if (id == R.id.iv_back) { // true表示AgentWeb处理了该事件
            mAgentWeb?.let {
                if (!it.back()) {
                    requireActivity().finish()
                }
            }
        } else if (id == R.id.iv_finish) {
            requireActivity().finish()
        } else if (id == R.id.iv_more) {
        } else if (id == R.id.iv_search) {
            mSimpleSearchView!!.showSearch()
        }
    }

    /**
     * 打开浏览器
     *
     * @param targetUrl 外部浏览器打开的地址
     */
    private fun openBrowser(targetUrl: String) {
        if (TextUtils.isEmpty(targetUrl) || targetUrl.startsWith("file://")) {
            Toast.makeText(this.context, "$targetUrl 该链接无法使用浏览器打开。", Toast.LENGTH_SHORT)
                .show()
            return
        }
        val intent = Intent()
        intent.setAction("android.intent.action.VIEW")
        val mUri = Uri.parse(targetUrl)
        intent.setData(mUri)
        startActivity(intent)
    }


    /**
     * 清除 WebView 缓存
     */
    private fun toCleanWebCache() {
        if (this.mAgentWeb != null) {
            //清理所有跟WebView相关的缓存 ，数据库， 历史记录 等。

            mAgentWeb!!.clearWebCache()
            Toast.makeText(activity, "已清理缓存", Toast.LENGTH_SHORT).show()
            //清空所有 AgentWeb 硬盘缓存，包括 WebView 的缓存 , AgentWeb 下载的图片 ，视频 ，apk 等文件。
//            AgentWebConfig.clearDiskCache(this.getContext());
        }
    }


    /**
     * 复制字符串
     *
     * @param context
     * @param text
     */
    private fun toCopy(context: Context, text: String) {
        val mClipboardManager =
            context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        mClipboardManager.setPrimaryClip(ClipData.newPlainText(null, text))
    }


    override fun onResume() {
        mAgentWeb!!.webLifeCycle.onResume() //恢复
        super.onResume()
    }

    override fun onPause() {
        mAgentWeb!!.webLifeCycle.onPause() //暂停应用内所有WebView ， 调用mWebView.resumeTimers();/mAgentWeb.getWebLifeCycle().onResume(); 恢复。
        super.onPause()
    }

    override fun onFragmentKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (mSimpleSearchView!!.onBackPressed()) {
            return true
        }
        return mAgentWeb!!.handleKeyEvent(keyCode, event)
    }

    override fun onDestroyView() {
        mAgentWeb!!.webLifeCycle.onDestroy()
        FileCompressor.getInstance().unregisterFileCompressEngine(this)
        super.onDestroyView()
    }

    /**
     * MiddlewareWebClientBase 是 AgentWeb 3.0.0 提供一个强大的功能，
     * 如果用户需要使用 AgentWeb 提供的功能， 不想重写 WebClientView方
     * 法覆盖AgentWeb提供的功能，那么 MiddlewareWebClientBase 是一个
     * 不错的选择 。
     * webviewclient
     * @return
     */
    protected val middlewareWebClient: MiddlewareWebClientBase
        get() = object : MiddlewareWebViewClient() {
            /**
             *
             * @param view
             * @param url
             * @return
             */
            /**
             *
             * @param view
             * @param url
             * @return
             */
            override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                Trace.e("MiddlewareWebClientBase#shouldOverrideUrlLoading url:$url")

                /*if (url.startsWith("agentweb")) { // 拦截 url，不执行 DefaultWebClient#shouldOverrideUrlLoading
					Trace.d( "agentweb scheme ~");
					return true;
				}*/
                if (super.shouldOverrideUrlLoading(
                        view,
                        url
                    )
                ) { // 执行 DefaultWebClient#shouldOverrideUrlLoading
                    return true
                }
                // do you work
                return false
            }

            override fun shouldOverrideUrlLoading(
                view: WebView,
                request: WebResourceRequest
            ): Boolean {
                Trace.e(
                    "MiddlewareWebClientBase#shouldOverrideUrlLoading request url:" + request.url.toString()
                )
                val url = request?.url.toString()
                if (url.contains(".mp4") || url.contains(".m3u8")) {
                    // 如果是视频链接，启动自定义播放器
                    ToastUtils.show("$url 播放")
                }
                return super.shouldOverrideUrlLoading(view, request)
            }

            override fun onReceivedError(
                view: WebView,
                request: WebResourceRequest,
                error: WebResourceError
            ) {
                if (request.isForMainFrame && error.errorCode != -1) {
                    super.onReceivedError(view, request, error)
                }
            }
        }.also { this.mMiddleWareWebClient = it }

    protected val middlewareWebChrome: MiddlewareWebChromeBase
        get() = object : MiddlewareChromeClient() {
        }.also { this.mMiddleWareWebChrome = it }

    /**
     * 选择文件后回调该方法， 这里可以做文件压缩 / 也可以做图片的方向调整
     *
     * @param type     customize/system  ， customize 表示通过js方式获取文件， 把文件
     * 转成base64的方式返回给js，这种方式兼容性高，但是存在文件过大转成base64时
     * 字符串长度过长，导致与js通信失败问题，所以很有必要压缩文件， 尽量控制字符串长度在512kb以内。
     * system 这种方式，是由input/file 标签触发的文件选择，这种方式缺点是在Android 4.4 不回调
     * fileChooser，存在兼容性问题，但是经过升级，基本可以忽略了，api 的兼容性越来越好了， 回调
     * 返回是于uri形式，所以不存在文件大小问题，作图片预览也很快。(推荐这种方式)
     * @param uri      文件的uri
     * @param callback
     */
    override fun compressFile(type: String, uri: Array<Uri>, callback: ValueCallback<Array<Uri>>) {
        Trace.e("compressFile type:$type")
    }

    fun canBack() {
        mAgentWeb?.let {
            if (!it.back()) {
                getAttachActivity()?.finish()
            }
        }
    }

    fun canForward() {
        mAgentWeb?.let {
            if (it.webCreator?.webView?.canGoForward() == true) {
                it.webCreator?.webView?.goForward()
            } else {
            }
        }
    }

    companion object {
        const val URL_KEY: String = "url_key"
        val TAG: String = ">>>>"
        fun getInstance(bundle: Bundle?): AgentWebFragment {
            val mAgentWebFragment = AgentWebFragment()
            if (bundle != null) {
                mAgentWebFragment.arguments = bundle
            }

            return mAgentWebFragment
        }
    }
}
